// 导入vue
import Vue from 'vue'
// 导入Vuex
import Vuex from 'vuex'

Vue.use(Vuex)
const state = {
	// 本地播放列表
	musicPlaylist: [],
	// 是否播放
	isPlay: false,
	// 当前音乐的索引值
	currentIndex: 0,
	// 定时器的唯一标识值
	timer: 0,
	// 音乐播放后的实时时间[秒]
	curTime: 0,
	// 当前播放音乐的总时长[秒]
	durationTimeSecond: 0,
	// 用于记录音乐是否是自然播放结束
	isEnded: 0,
	// 登录用户id/token/cookie
	userInfo: {}
}
const actions = {
	changeMusicPlaylist({ commit }, musicPlaylist) {
		// 得到数据进行一系列的处理
		const temp = musicPlaylist
		const arr = []
		temp.forEach(v => {
			arr.push({
				al: v.al,
				ar: v.ar,
				id: v.id,
				name: v.name
			})
		})
		commit('CHANGEMUSICPLAYLIST', arr)
		uni.setStorageSync('musicPlaylist', arr)
	},
	changeCurrentIndex({commit, state}, params) {
		// console.log('触发l')
		return new Promise((resolve, reject) => {
			commit('CHANGECURRENTINDEX', params)
			resolve(state.currentIndex)
		})
	}
}
const mutations = {
	CHANGEMUSICPLAYLIST(state, arr) {
		state.musicPlaylist = arr
	},
	PLAYPUASE(state, isPlay) {
		state.isPlay = isPlay
	},
	CURRENTINDEX(state, index) {
		state.currentIndex = index
	},
	CHANGECURRENTINDEX(state, {type}) {
		if (type === 'pre') {
			// 如果当前播放的音乐索引值为0,则播放最后一曲,否则自减1
			state.currentIndex = state.currentIndex === 0? (state.musicPlaylist.length - 1) : state.currentIndex - 1
		} else if (type === 'next') {
			// 如果当前播放的音乐索引值为最后一个,则播放最后一曲,否则自增1
			state.currentIndex = state.currentIndex === state.musicPlaylist.length - 1? 0 : state.currentIndex + 1
		}
		// 实时更新本地存储中的索引值数据
		uni.setStorageSync('curIndex', state.currentIndex)
	},
	// 存储用户id
	SETUSERINFO(state, info) {
		state.userInfo = info
	},
	HANDLETIME(state, durationTimeSecond) {
		// 清除所有,开启新的
		clearInterval(state.timer)
		state.timer = setInterval(() => {
			// 音乐进度条每过一秒自动增加
			state.curTime++
			if (state.curTime >= durationTimeSecond) {
				// 清除定时器
				clearInterval(state.timer)
				// 重置时间
				state.curTime = 0
				// 停止播放[把state中控制是否播放的数据设置为false]
				state.isPlay = false
			}
		}, 1000)
	},
	RESETTIME(state) {
		// 重置时间
		state.curTime = 0
	},
	RENEWCURTIME(state, newTime) {
		// 拖动进度条后更新
		state.curTime = newTime
	},
	DURATIONTIMESECOND(state, time) {
		state.durationTimeSecond = Math.floor(time / 1000)
	},
	CHANGEISENDED(state) {
		state.isEnded++
	}
}
const getters = {}
export default new Vuex.Store({
	state,
	mutations,
	actions,
	getters
})
